from jinja2 import Template


class LogstashTemplate:
    category = ''

    # 出厂设置
    Init = """
    input {}
    filter {drop{}}
    output {}
    """

    # 配置模板
    Input = """
    input {
      {{category}} {
        port => {{port}}
        add_field => {
          "_sourceid" => "{{id}}"
          "category" => "{{category}}"
          }
        }
      }
    """

    Filter = """"""

    Output = """

    output {
      kafka {
        retries => 3
        batch_size => 16384
        max_request_size => 1048576
        compression_type => "snappy"
        linger_ms => 100
        topic_id => "todo_parser_queue"
        bootstrap_servers => "192.168.101.79:9092"
        codec => "json"
      }
    }"""  # 根据需要可以添加kafka密码

    @classmethod
    def render(cls, category, host, port, id, configure):
      template = Template(cls.Input) 
      return template.render(category=category, host=host, port=port, id=id, configure=configure)


class SyslogLogstash(LogstashTemplate):
    category = 'syslog'


class TCPLogstash(LogstashTemplate):
    category = 'tcp'


class UDPLogstash(LogstashTemplate):
    category = 'udp'


class KafkaLogstash(LogstashTemplate):
    category = 'kafka'
    Input = """
    input {
      kafka {
        bootstrap_servers => "{{host}}:{{port}}"
        {% for k, v in configure.items() %}{{k}} => {{v}}
        {% endfor %}
        add_field => {
          "_sourceid" => "{{id}}"
          "category" => "{{category}}"
          }
        codec => 'json'
        }
      }
    """


class HttpLogstash(LogstashTemplate):
    category = 'http'
    Input = """
    input {
      http {
        port => {{port}}
        codec => 'plain'
        add_field => {
          "_sourceid" => "{{id}}"
          "category" => "{{category}}"
          }
        }
      }
    """

LogstashMap = {item.category: item for item in LogstashTemplate.__subclasses__()}


FilebeatTPL = """
filebeat:
  inputs:
  - enabled: true
    paths:
    - /var/log/*.log
    type: log
logging:
  level: error
  metrics:
    enabled: false
    period: 30s
  to_files: false
output:
  logstash:
    compression_level: 3
    enabled: true
    hosts:
    - {{HostIP}}:5014
"""


WinLogBeatTPL = """
logging:
  level: error
  metrics:
    enabled: false
    period: 30s
  to_files: false
processors:
- rename:
    fail_on_error: false
    fields:
    - from: message
      to: winlog.message
    ignore_missing: true
- drop_fields:
    fields:
    - message
    - winlog.keywords
    - winlog.api
- rename:
    fields:
    - from: log.level
      to: winlog.level
    ignore_missing: true
- rename:
    fields:
    - from: event.kind
      to: winlog.kind
    ignore_missing: true
- rename:
    fields:
    - from: event.created
      to: winlog.start
    ignore_missing: true
- rename:
    fields:
    - from: host.name
      to: winlog.hostname
    ignore_missing: true
- rename:
    fields:
    - from: winlog.event_data
      to: winlog.EventData
    ignore_missing: true
- rename:
    fields:
    - from: winlog
      to: message
    ignore_missing: true
winlogbeat:
  event_logs:
  - name: Application
  - name: System
  - name: Security
output:
  logstash:
    codec:
      format:
        string: '%{[message]}'
    compression_level: 3
    hosts:
    - {{HostIP}}:5014
"""


MetricBeatTPL = """
fields:
  domain: Default
logging:
  level: error
  metrics:
    enabled: false
    period: 30s
  to_files: false
metricbeat:
  config:
    modules:
      path: ${path.config}/modules.d/xyz.yml
      reload:
        enabled: false
  modules:
  - core:
      metrics:
      - percentages
    cpu:
      metrics:
      - percentages
      - normalized_percentages
    enabled: true
    metricsets:
    - cpu
    - load
    - memory
    - network
    - process
    - process_summary
    - uptime
    - socket_summary
    - core
    - diskio
    - filesystem
    - fsstat
    - service
    module: system
    period: 10s
    process:
      cgroups:
        enabled: true
      include_top_n:
        by_cpu: 200
        by_memory: 200
        enabled: true
    processes:
    - .*
output:
  logstash:
    compression_level: 3
    enabled: true
    hosts:
    - {{HostIP}}:5014
processors:
- add_host_metadata: null
"""


if __name__ == '__main__':
    data = LogstashMap['tcp'].render(category='tcp', port=10, id='aa', configure={})
    print(data)

    data = LogstashMap['udp'].render(category='udp', port=10, id='aa', configure={})
    print(data)

    data = LogstashMap['syslog'].render(category='syslog', port=10, id='aa', configure={})
    print(data)

    data = LogstashMap['kafka'].render(category='kafka', port=9092, id='aa',  host='192.168.1.1',
                                       configure={'topics': ["a", "b"], 'group_id': 'aa', 'auto_offset_reset': 'latest'})
    print(data)

    data = LogstashMap['http'].render(category='http', port=9092, id='aa', configure={'headers': ['cookie', 'user-Agent']})
    print(data)
